﻿using System;
using System.Threading.Tasks;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using WPFNote.Services.IDal;
using WPFNote.Utilities.Extensions;

namespace WPFNote.ViewModels {
    public class LoginViewModel : BindableBase, IDialogAware {
        public bool CanCloseDialog() {
            return true;
        }

        public void OnDialogClosed() {
            LoginOut();
        }

        public void OnDialogOpened(IDialogParameters parameters) {
        }

        public string Title { get; set; } = "BlackvonNote";

        public event Action<IDialogResult> RequestClose;

        #region LoginExec

        private string _userName;

        public string UserName {
            get => _userName;
            set {
                _userName = value;
                RaisePropertyChanged();
            }
        }

        private string _password;

        public string Password {
            get => _password;
            set {
                _password = value;
                RaisePropertyChanged();
            }
        }

        private IUsers _users;
        private readonly IEventAggregator _aggregator;
        public DelegateCommand LoginCommand { get; set; }
        public DelegateCommand OpenWebCommand { get; set; }
        public DelegateCommand ForgetPasswordCommand { get; set; }

        public LoginViewModel(IEventAggregator aggregator, IUsers users) {
            _aggregator = aggregator;
            _users = users;
            LoginCommand = new DelegateCommand(ToLogin);
            OpenWebCommand = new DelegateCommand(OpenWeb);
        }

        private void OpenWeb() {
        }

        private async void ToLogin() {
            if (string.IsNullOrWhiteSpace(UserName) ||
                string.IsNullOrWhiteSpace(Password)) {
                _aggregator.SendMessage("用户名和密码不能为空", "Login");
                return;
            }

            var (isOk, message) = await new Services.Login(_users).Auth(UserName, Password);
            if (isOk) {
                _aggregator.SendMessage(message, "Login");
                RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
            } else {
                _aggregator.SendMessage(message, "Login");
            }
        }

        private void LoginOut() {
            RequestClose?.Invoke(new DialogResult(ButtonResult.No));
        }

        #endregion
    }
}